<template>
  <div>
    <el-table
      ref="tableRef"
      :data="convertedTableData"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center', padding: '0' }"
      :cell-class-name="cellStyle"
      @selection-change="handleSelectionChange"
      border
      :row-style="{ height: '40px' }"
      row-key="地址"
      style="width: 1200px"
      height="400px"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column
        v-for="(header, index) in tableHeader"
        :key="index"
        :prop="header.toLowerCase()"
        :label="header"
        :width="widthList[index]"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-button
            v-if="header === TableHeader.Read"
            circle
            style="color: #409eff; border: none"
            @click="readRegister(scope.$index)"
          >
            <el-icon><RefreshRight /></el-icon>
          </el-button>
          <!-- 条件渲染最后一行的标签 -->
          <el-tag
            v-if="header === TableHeader.Status"
            :type="getTagType(scope.row[header])"
          >
            {{ scope.row[header] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 15, 20, 50, 100]"
      :page-size="pageSize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
  </div>
</template>

<script setup lang="ts" name="Table">
import { ref, computed, type PropType, nextTick, reactive } from 'vue'
import { useDeviceStore } from '@/stores/device.ts'
import { storeToRefs } from 'pinia';
import { Status, TableHeader, type TableRow,type TableDataRow } from '@/types/device.ts';
const deviceStore = useDeviceStore();
const { selectedRows } = storeToRefs(deviceStore); // 解构保持响应式
const tableRef = ref();

const props = defineProps({
  deviceName: {
    type: String,
    required: true
  },
  slaveId: {
    type: Number,
    required: true
  },
  registerType: {
    type: Number,
    required: true
  },
  tableHeader: {
    type: Array as PropType<string[]>,
    required: true
  },
  tableData: {
    type: Array as PropType<TableRow[]>,
    required: true
  }
})

// 计算属性
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => {
  return Math.ceil(props.tableData.length);
})

// 方法
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}

// 响应式状态
const widthList = ref([300, 300, 100, 150, 300])
const handleSelectionChange = (rows: TableDataRow[]) => {
  selectedRows.value = reactive([...rows]); // 存储所有选中的行
};

const convertedTableData = computed<TableDataRow[]>(() => {
  const data = props.tableData.map(row => {
    const rowData: TableDataRow = {}
    rowData[TableHeader.Address] = row.address
    rowData[TableHeader.RegisterValue] = row.value
    if (row.status === undefined){
       rowData[TableHeader.Status] = Status.Pending
    }else{
      rowData[TableHeader.Status] = row.status === true ? Status.Success : Status.Error
    }
    rowData[TableHeader.LastUpateTime] = row.time
    return rowData;
  })
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

const getTagType = (value: string) => {
  switch (value) {
    case Status.Pending: return 'warning'
    case Status.Success: return 'success'
    case Status.Error: return 'danger'
    default: return 'info'
  }
}

const cellStyle = () => 'cell-style'

const readRegister = async(index: number) => {
  const row = convertedTableData.value[index]
  const address = row[TableHeader.Address]
  const data = await deviceStore.readRegister(props.deviceName,props.slaveId, props.registerType, address, address);
  const findIndex = props.tableData.findIndex(row => row.address === address)
  if (findIndex !== -1 && data.length>0) {
    updateRow(findIndex, data[0]);
    // 同时更新selectRows的值
    deviceStore.updateSelectedRows(address, data[0]);
  }else{
    const errorDataRow = {
      address,
      value: null,
      status: Status.Error,
      time: new Date().toLocaleString()
    }
    updateRow(findIndex, errorDataRow);
    deviceStore.updateSelectedRows(address, errorDataRow);
  }

  nextTick(() => {
    selectedRows.value.forEach(row => {
      const targetRow = convertedTableData.value.find(item => item[TableHeader.Address] === row[TableHeader.Address]);
      if (targetRow) {
        tableRef.value?.toggleRowSelection(targetRow, true);
      }
    });
  });
}

const updateRow = (index:number, newData:any) => {
  props.tableData.splice(index, 1, {
    ...props.tableData[index],
    value: newData.value,
    status: newData.status,
    time: newData.time
  });
}
</script>

<style>
.el-pagination {
  margin-top: 10px;
  text-align: right;
}

.cell-style {
  text-align: center; /* 单元格文字居中 */
  height: 30px;
  line-height: 30px;
  font-size: 14px;
}

.el-table .el-table__cell {
  height: 30px; /* 行高 */
  line-height: 30px; /* 文字垂直居中 */
}
</style>
